// $Id$
// Licensed under Apache License Version 2.0
// See: http://www.apache.org/licenses/LICENSE-2.0.html
package de.servicezombie.tests;

import org.springframework.beans.BeanUtils;
import org.testng.Assert;

/**
 * Extends default TestNG asserts
 */
public class SzAssert {

	public static void assertTypeOf(Object bean, Class<?> requiredType) {
		Assert.assertTrue(requiredType.isAssignableFrom(bean.getClass()));
	}
	
	/**
	 * assert a property of the same name exists and has the same values
	 */
	public static void assertPropertyEquals(Object left, Object right, String propertyName) {

		Object leftValue = null;
		Object rightValue = null;

		try {
			leftValue = BeanUtils.getPropertyDescriptor(left.getClass(), propertyName)
					.getReadMethod().invoke(left);
			rightValue = BeanUtils.getPropertyDescriptor(left.getClass(), propertyName)
					.getReadMethod().invoke(right);
		}
		catch (Exception e) {
			new AssertionError("unable to call get methods: " + e.getMessage());
		}

		if(leftValue.getClass().isArray()) {
			Object[] l = (Object[]) leftValue;
			Object[] r = (Object[]) rightValue;
			
			for(int i = 0; i < l.length; i++) {
				Assert.assertEquals(l[i], r[i], 
						"properties are not equal in array at index " + i 
						+": (" + propertyName + ", " + left + ", " + right + ")");	
			}
		}
		else {
			Assert.assertEquals(leftValue, rightValue, 
					"properties are not equal: (" + propertyName + ", " + left + ", " + right + ")");			
		}
		
	}
}
